import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from Config.globalconfig import report_path,log_path


class MailManage:
    # 访问文件夹，通过下标找到文件并return
    def add_attachment(self, attach_dir):
        list = os.listdir(attach_dir)
        list1 = sorted(list)
        attach = os.path.join(attach_dir, list1[0])
        return attach

    def sendReport(self, filename):
        # 设置发件人、收件人和主题
        sender = 'wyh2085195880@163.com'
        receiver = 'wyh2085195880@163.com'
        subject = '头部标题'

        # 创建邮件对象
        msg = MIMEMultipart()  # 生成包含多个部分的邮件体 MINE 对象
        msg['From'] = sender
        msg['To'] = receiver
        msg['Subject'] = subject
        # 添加邮件正文
        msg.attach(MIMEText('吴宇辉的测试报告', 'plain'))

        # 添加附件
        with open(filename, 'rb') as f:  # filename为add_attachment方法返回的attach文件
            attachment = MIMEApplication(f.read(), Name=filename)  # 发送附件的方法（文件内容、文件名称）
            # 指定附件类型attachment（表示附件应该被下载保存），或者设置为inline直接显示在内部
            attachment['Content-Disposition'] = 'attachment; filename="%s"' % filename
            msg.attach(attachment)

        # 连接SMTP服务器并发送邮件
        smtp_server = 'smtp.163.com'  # SMTP服务器
        smtp_port = 465  # 端口号
        smtp_username = 'wyh2085195880@163.com'  # 账户名
        smtp_password = 'KNEMUTGQFDHORHPE'  # 授权码

        try:
            with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:  # 连接服务器与端口
                server.login(smtp_username, smtp_password)  # 登录
                server.sendmail(sender, receiver, msg.as_string())  # 发送邮件
                server.close()  # 关闭服务
            print('Email with attachment sent successfully.')
        except smtplib.SMTPException as e:  # 失败时抓取错误信息
            print('Email with attachment sent fail.')
            print(e)


if __name__ == "__main__":
    ClassMailManage = MailManage()
    attach_dir = log_path  # 文件夹路径
    filename = ClassMailManage.add_attachment(attach_dir)  # 给此方法传递目录，方法返回一个文件
    ClassMailManage.sendReport(filename)  # 把文件传入此方法并运行
